// 图片上传相关工具函数
import request from '@/utils/request'

// 图片压缩函数
export function compressImage(file: File, maxWidth = 1920, maxHeight = 1080, quality = 0.8): Promise<File> {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')!
    const img = new Image()
    
    img.onload = () => {
      // 计算压缩后的尺寸
      let { width, height } = img
      
      if (width > maxWidth || height > maxHeight) {
        const ratio = Math.min(maxWidth / width, maxHeight / height)
        width *= ratio
        height *= ratio
      }
      
      // 设置canvas尺寸
      canvas.width = width
      canvas.height = height
      
      // 绘制图片
      ctx.drawImage(img, 0, 0, width, height)
      
      // 转换为blob
      canvas.toBlob((blob) => {
        if (blob) {
          const compressedFile = new File([blob], file.name, {
            type: file.type,
            lastModified: Date.now()
          })
          resolve(compressedFile)
        } else {
          resolve(file)
        }
      }, file.type, quality)
    }
    
    img.src = URL.createObjectURL(file)
  })
}

// 图片文件验证
export function validateImageFile(file: File): { valid: boolean; message?: string } {
  // 检查文件类型
  const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!validTypes.includes(file.type)) {
    return {
      valid: false,
      message: '只支持 JPEG、PNG、GIF、WebP 格式的图片'
    }
  }
  
  // 检查文件大小 (10MB)
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    return {
      valid: false,
      message: '图片大小不能超过 10MB'
    }
  }
  
  return { valid: true }
}

// 生成图片预览URL
export function createImagePreview(file: File): string {
  return URL.createObjectURL(file)
}

// 清理预览URL
export function revokeImagePreview(url: string): void {
  URL.revokeObjectURL(url)
}

// 图片上传到服务器（使用封装的request）
export async function uploadImageToServer(file: File): Promise<{ url: string; id?: string }> {
  try {
    const formData = new FormData()
    formData.append('image', file)
    formData.append('type', 'editor') // 标识来源
    
    // 使用封装的 request，接口地址待定
    const response = await request.post('/api/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000 // 上传文件需要更长超时时间
    })
    
    // 假设后端返回格式：{ url: string, id?: string }
    return {
      url: response.data.url,
      id: response.data.id
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    throw new Error('图片上传失败，请重试')
  }
}

// 处理图片上传的完整流程
export async function handleImageUpload(
  file: File,
  options: {
    compress?: boolean
    maxWidth?: number
    maxHeight?: number
    quality?: number
  } = {}
): Promise<{ url: string; id?: string }> {
  const { compress = true, maxWidth = 1920, maxHeight = 1080, quality = 0.8 } = options
  
  // 验证文件
  const validation = validateImageFile(file)
  if (!validation.valid) {
    throw new Error(validation.message)
  }
  
  let fileToUpload = file
  
  // 压缩图片（如果需要）
  if (compress) {
    fileToUpload = await compressImage(file, maxWidth, maxHeight, quality)
  }
  
  // 上传到服务器
  return await uploadImageToServer(fileToUpload)
}

// Base64转文件
export function base64ToFile(base64: string, filename: string): File {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)![1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  
  return new File([u8arr], filename, { type: mime })
}

// 文件转Base64
export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = error => reject(error)
  })
} 